package com.i2863.shiroDemo.util;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.qiniu.common.Zone;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.apache.http.impl.client.CloseableHttpClient;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/12/1.
 */
public class QiNiuUtil {
    public static String ak = "LplD_2KC-o7-3omKyCTgXjnHgPUITUFm6F0ck-T0";
    public static String sk = "ENZvx9UweRe8ekH1po7ffovDiapDqZS8UltW9wal";
    public static String bucket = "images-bucket";
    public static String baseURL = "http://images-cdn.adun.ccsobey.com/";
    //    public static String uploadToken = Auth.create(ak, sk).uploadToken(bucket);
    private static CloseableHttpClient client = HttpSessionUtils.buildHttpClient();

    public static UploadManager getUploadManager() {
        Zone z = Zone.autoZone();
        Configuration c = new Configuration(z);
        return new UploadManager(c);
    }

    //根据站点ID获取七牛上传域
    public static Map<String, Object> getUploadManagerForSiteid(Integer siteId) throws IOException {
        final String url = "http://vms.i2863.com/api";
        Map<String, String> params = new HashMap<>();
        params.put("method", "orgInfo");
        params.put("siteId", siteId.toString());
        String result = HttpSessionUtils.httpPost(client, url, params);
        JsonObject json = new JsonParser().parse(result).getAsJsonObject();
        JsonObject data = json.get("data").getAsJsonObject();

        String token = Auth.create(data.get("ak").getAsString(), data.get("sk").getAsString()).uploadToken(data.get("bucket").getAsString());
        Zone z = Zone.autoZone();
        Configuration c = new Configuration(z);
        UploadManager uploadManager = new UploadManager(c);
        String host = data.get("host").getAsString();
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("uploadManager", uploadManager);
        map.put("host", host);
        return map;
    }

    public static void main(String[] args) {
        try {
            getUploadManagerForSiteid(127);
        } catch (IOException ignored) {

        }
    }

}
